import { Component, Injector, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LazyLoadEvent, SelectItem, TreeNode } from 'primeng/api';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';
import { DataExportComponent } from '@app/admin/bop/data-export/data-export.component'
import { QualityPlatformServiceProxy, CommonServiceProxy } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { MessageService } from '@abp/message/message.service';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { Paginator } from 'primeng/components/paginator/paginator';
@Component({
    selector: 'app-summarystatistics',
    templateUrl: './envelopestatistics.component.html',
    styleUrls: ['./envelopestatistics.component.less']
})
export class EnvelopestatisticsComponent extends AppComponentBase {
    @ViewChild('dataexport') dataExport: DataExportComponent;
    @ViewChild('paginator') paginator: Paginator;
    selectedOu: TreeNode;
    userform: FormGroup;//右侧form
    selectedColumns: any;//表名查询下啦
    //模型下拉数据
    Models = []
    //搜索时的model值
    modelValue = undefined
    //发次下拉数据
    LotNoList = []
    //发次值
    lotNo = undefined
    //对比发次
    dblotNo = undefined
    genders = [];
    tablemodel = undefined//表结构v-model
    //树数据
    treeData = [];
    workStepData: [];//工步动态表List
    selectedFiles: TreeNode;
    workStepHeader: any;//工步动态表Header
    loadingtree: boolean;
    ischeckTree: any;//点击数节点信息
    rowBrandGroup: any;

    constructor(
        injector: Injector,
        private _qualityPlatformServiceProxy: QualityPlatformServiceProxy,
        private _fileDownloadService: FileDownloadService,
        private _commonServiceProxy: CommonServiceProxy,
        private _messageService: MessageService
    ) {
        super(injector);

    }
    onSort() {
        let that = this;
        switch (that.tablemodel) {
            case '力矩记录表': {
                this.BrandRowGroupData("fisrtDrawingNum");
                break;
            }
            case '多媒体记录表': {
                this.BrandRowGroupData("recordLocation");
                //语句
                break;
            }
            default: {
                //语句
                break;
            }

        }
    }
    reportTo() {
        //质量报告
        window.open('http://10.20.253.10:10080/webroot/decision/view/report?viewlet=Developments/57Quality/包络.cpt', '_blank');
    }
    //表格切换事件
    changeDropDown(e) {
        this.workStepData = [];
        this.workStepHeader = [];
        //重置页码
        if (this.paginator) {
            this.paginator._first = 0;
            this.paginator._rows = 10;
        }
    }
    //合并表结构
    BrandRowGroupData(key) {
        this.rowBrandGroup = {};
        if (this.workStepData) {
            for (let i = 0; i < this.workStepData.length; i++) {
                let rowData = this.workStepData[i];
                let brand = rowData;
                if (i == 0) {
                    this.rowBrandGroup[brand[key]] = { index: 0, size: 1 };
                }
                else {
                    let previousRowData = this.workStepData[i - 1];
                    let previousRowGroup = previousRowData;
                    if (brand[key] === previousRowGroup[key]
                    ) {
                        this.rowBrandGroup[brand[key]].size++;
                    }
                    else
                        this.rowBrandGroup[brand[key]] = { index: i, size: 1 };
                }
            }
        }
    }
    //全部展开
    expandAll() {
        this.treeData.forEach((node) => {
            this.expandRecursive(node, true);
        });
    }
    //导出
    exportToExcel(): void {
        if (!Boolean(this.modelValue && this.lotNo)) {
            this._messageService.warn('请先选择型号和发次!')
            return
        }
        if (!Boolean(this.ischeckTree)) {
            this._messageService.warn('请先选择树节点!')
            return
        }
        if (!Boolean(this.tablemodel)) {
            this._messageService.warn('请先选择表信息!')
            return
        }
        this._qualityPlatformServiceProxy.exportReportExcel(
            this.modelValue, this.lotNo, this.ischeckTree ? this.ischeckTree.id : '',
            this.tablemodel, '', '', '', '', '', '', this.ischeckTree.key != -1 ? false : true,
            this.ischeckTree.nodeLevel, true,this.dblotNo,true)
            .subscribe(result => {
                // this._fileDownloadService.downloadTempFile(result);
                window.open(result);
                URL.revokeObjectURL(result);
            });
    }
    //导出
    export(): void {
        if (!Boolean(this.modelValue && this.lotNo)) {
            this._messageService.warn('请先选择型号和发次!')
            return
        }
        if (!Boolean(this.ischeckTree)) {
            this._messageService.warn('请先选择树节点!')
            return
        }
        if (!Boolean(this.tablemodel)) {
            this._messageService.warn('请先选择表信息!')
            return
        }
        this._qualityPlatformServiceProxy.exportReportExcel(
            this.modelValue, this.lotNo, this.ischeckTree ? this.ischeckTree.id : '',
            this.tablemodel, '', '', '', '', '', '', this.ischeckTree.key != -1 ? false : true,
            this.ischeckTree.nodeLevel, true,this.dblotNo,false)
            .subscribe(result => {
                // this._fileDownloadService.downloadTempFile(result);
                window.open(result);
                URL.revokeObjectURL(result);
            });
    }

    private expandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }
    //点击树节点
    nodeSelect(event) {
        this.ischeckTree = event.node;
    }
    //根据表名搜索
    searchRight() {
        if (!Boolean(this.modelValue && this.lotNo && this.dblotNo && this.dblotNo.length > 0)) {
            this._messageService.warn('请先选择型号和发次和对比发次!')
            return
        }
        if (!Boolean(this.ischeckTree)) {
            this._messageService.warn('请先选择树节点!')
            return
        }
        if (!Boolean(this.tablemodel)) {
            this._messageService.warn('请先选择表信息!')
            return
        }
        /// <param name="model">型号</param>
        /// <param name="lotstr">发次</param>
        /// <param name="nodeId">节点Id</param>
        /// <param name="tableNameStr">多表名称 以逗号隔开</param>
        /// <param name="FisrtDrawingNum">图号/代号</param>
        /// <param name="FirstDrawingName">图号名称</param>
        /// <param name="SecondDrawingNum">零件2代号</param>
        /// <param name="SecondDrawingName">零件2名称</param>
        /// <param name="ToolUsed">所用工具编号</param>
        /// <param name="RecordElementStr">记录项目</param>
        /// <param name="ShowAll">node节点是否为空 true则 无需选中节点</param>
        /// <param name="DisplayRoute">是否显示路径 true显示 </param>
        /// <param name="nodeLevel">节点层级 默认是节点 8为工序 9 为工步</param>
        /// <param name="reachTable">刷新分页的当前表名</param>
        /// <param name="envelope">是否包络，true 包络</param>
        /// <param name="pageIndex">查询的页数 </param>
        /// <param name="pageSize">每页显示的个数</param>
        /// <param name="paging">是否开启分页 默认为true分页,false不开启分页</param>
        this._qualityPlatformServiceProxy.statisticalReport(this.modelValue,
            this.lotNo , this.ischeckTree ? this.ischeckTree.id : '',
            this.tablemodel, '', '', '', '', '', '', this.ischeckTree.key != -1 ? false : true,
            false, this.ischeckTree ? this.ischeckTree.nodeLevel : undefined,
            this.workStepHeader ? this.workStepHeader.tableName : undefined,
            true, this.paginator ? this.paginator.getPage() + 1 : 1,
            this.paginator ? this.paginator._rows : 10, true,this.dblotNo,undefined,false,true)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                if (result.tableNameDictionary.length == 0) {
                    this._messageService.info('暂无数据！')
                    return
                }
                this.workStepHeader = result.tableNameDictionary[0];
                this.workStepData = this.workStepHeader ? result.workStepOut[result.tableNameDictionary[0].tableKey] : [];

            });
    }

    //处理图片
    getImage(item) {
        // this.images=[{source:'https://scpic.chinaz.net/files/pic/pic9/202105/bpic23276.jpg', thumbnail: 'https://scpic.chinaz.net/files/pic/pic9/202105/bpic23276.jpg', title:'Sopranos 1'}];
        let imageList = item ? item.split(',') : []
        let result = []
        imageList.forEach((e, i) => {
            if (e.includes('.mp4')) {
            } else {
                let a = e.split('_');
                a[a.length - 1] = a[a.length - 1].replace('thumbnail', '');
                let rs = a.join('');
                result.push({
                    source: rs,
                    thumbnail: rs,
                    title: ''
                })
            }
        })
        return result
    }
    getVideo(item) {
        let imageList = item ? item.split(',') : []
        let result = []
        imageList.forEach((e, i) => {
            if (e.includes('.mp4')) {
                result.push({
                    source: e,
                    thumbnail: e,
                    title: ''
                })
            }
        })
        return result
    }
    //树搜索
    treeSearch() {
        if (!Boolean(this.modelValue && this.lotNo)) {
            this._messageService.warn('请先选择型号和发次!')
            return
        }
        this._qualityPlatformServiceProxy.getTreeContainRoot(this.lotNo, this.modelValue)
            .pipe(finalize(() => { })).subscribe(result => {
                this.treeData = [];
                this.treeData.push({
                    ...result.parentNode,
                    key: -1,
                    nodeDrawingNo: result.parentNode.drawingNo,
                    nodeName: result.parentNode.modelName,
                    model: result.parentNode.model,
                    lotNo: result.parentNode.lotNo,
                    stageSign: result.parentNode.stageSign,
                    children: result.childNodes
                })
                this.expandAll();
            })
    }
    //获取表名
    getTableName() {
        this.genders = [];
        this._qualityPlatformServiceProxy.getAnalysisTableList(undefined, 1)
            .pipe(finalize(() => { })).subscribe(result => {
                result.forEach(item => {
                    this.genders.push({
                        label: item.tableName,
                        value: item.tableName
                    })
                })
            })
    }
    ngOnInit() {
        //获取型号下拉
        this.Models = [
            {
                label: '请选择',
                value: undefined
            }
        ];
        this._qualityPlatformServiceProxy.getModelNameList(undefined)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                for (const item of result) {
                    let data = { label: undefined, value: undefined };
                    data.label = item;
                    data.value = item;
                    this.Models.push(data);
                }
            });
        //获取表名称
        this.getTableName()
    }
    onChange(event) {
        //获取发次
        this.LotNoList = [
            {
                label: '请选择',
                value: undefined
            }
        ];
        this._qualityPlatformServiceProxy.getLotNoList(undefined,this.modelValue)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                for (const item of result) {
                    let data = { label: undefined, value: undefined };
                    data.label = item;
                    data.value = item;
                    this.LotNoList.push(data);
                }
            });
    }

}

